from urllib import urlencode, quote
from urllib2 import Request, urlopen
from xml.dom.minidom import parseString
from time import time

class GReaderConnection(object):
    
    auth_header = None
    feed_names = None
    last_token = None
    
    def __init__(self, username, password):
        self.username = username
        self.password = password
        
    def getAuthHeader(self):
        if self.auth_header == None:
            self.authenticate()
        return self.auth_header
        
    def authenticate(self):
        # Authenticate to obtain SID
        auth_url = 'https://www.google.com/accounts/ClientLogin'
        auth_req_data = urlencode({'Email': self.username,
                                   'Passwd': self.password,
                                   'service': 'reader'})
        auth_req = Request(auth_url, data=auth_req_data)
        auth_resp = urlopen(auth_req)
        auth_resp_content = auth_resp.read()
        auth_resp_dict = dict(x.split('=') \
                              for x in auth_resp_content.split('\n') if x)
        AUTH = auth_resp_dict["Auth"]
        # Create a header using the AUTH key 
        self.auth_header = {"Authorization" : "GoogleLogin auth=%s"%AUTH}
        
    def u(self, url_postfix):
        return "https://www.google.com/reader/" + str(url_postfix)
    
    def request(self, url_postfix):
        request = Request(self.u(url_postfix), None, self.getAuthHeader())
        response = urlopen(request)
        xml = response.read()
        return parseString(xml)
    
    def requestPlain(self, url_postfix):
        request = Request(self.u(url_postfix), None, self.getAuthHeader())
        response = urlopen(request)
        return response.read()
    
    def getToken(self):
        token = self.requestPlain('api/0/token')
        print "\tgot new token:" + str(token)
        return token
    
    def refreshToken(self, force):
        if self.last_token == None or force:
            self.last_token = self.getToken()
    
    def markAsRead(self, gid):
        self.refreshToken(False)
        for _ in range(2):
            url = "http://www.google.com/reader/api/0/edit-tag"
            values = {'i' : gid, 'a' : 'user/-/state/com.google/read', 
                      'ac' : 'edit', 'T' : self.last_token}
            data = urlencode(values)
            req = Request(url, data, self.getAuthHeader())
            response = urlopen(req)
            the_page = str(response.read())
            if the_page == "OK":
                return
            self.refreshToken(True)
        raise Exception(" could not mark as read");
    
    def requestUnread(self, feed_url):
        timestamp = str(int(time()))
        feed_url = quote(feed_url.encode('utf-8'))
        return self.request(("atom/" + str(feed_url) + "?ck=" + 
                      timestamp + "&xt=user/-/state/com.google/read"))
    
    def getFeeds(self): 
        if self.feed_names == None:
            # fetch subscription list
            self.feed_names = {}
            sub_list_dom = self.request("api/0/subscription/list")
            for sub_item in sub_list_dom.firstChild.firstChild.childNodes:
                sub_id = sub_item.childNodes[0].firstChild.data
                sub_name = sub_item.childNodes[1].firstChild.data
                self.feed_names[sub_id] = sub_name
        return self.feed_names
        